'use strict'
var FinanceModel = require('../../model/finance');
var OrganizationModel = require('../../model/organization')
var Data = require('../../util/data')

class Finance {
    async getAll(req, res, next) {
        try {
            const finances = await FinanceModel.find({});
            res.send(finances);
        } catch (err) {
            res.send(Data.throwError('获取资金数据失败'))
        }
    }
    async get(req, res, next) {
        try {
            const id = req.params.id
            const finance = await FinanceModel.findOne({ '_id': id });
            res.send(finance);
        } catch (err) {
            res.send(Data.throwError('获取资金数据失败'))
        }
    }
    async post(req, res, next) {
        try {
            const item = req.body
            if (!item.organizationId) {
                throw new Error('缺少组织！')
            } else {
                const finances = await FinanceModel.insertMany(item);
                const finance = finances[0]
                const organization = await OrganizationModel.findById(item.organizationId)
                organization.financeId = finance._id
                await OrganizationModel.findByIdAndUpdate(item.organizationId, organization)
                res.send(finance);
            }
        } catch (err) {
            res.send(Data.throwError('创建资金数据失败'))
        }
    }
    async delete(req, res, next) {
        try {
            const id = req.params.id
            const finance = await FinanceModel.deleteOne({ _id: id });
            res.send(finance);
        } catch (err) {
            res.send(Data.throwError('删除资金数据失败'))
        }
    }
    async put(req, res, next) {
        try {
            const id = req.params.id
            const data = req.body
            const finance = await FinanceModel.update({ _id: id }, data);
            res.send(finance);
        } catch (err) {
            res.send(Data.throwError('修改资金数据失败'))
        }
    }
}

module.exports = new Finance()